package com.turing.post.antimoney.impl;

import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.turing.post.antimoney.util.AlarmInfo;
import com.turing.post.antimoney.util.AlarmInfoDao;
import com.turing.post.antimoney.util.AlarmInfoDetail;
import com.turing.post.antimoney.util.AlarmInfoDetailDao;
import com.turing.post.antimoney.util.AlarmRule;
import com.turing.post.antimoney.util.AlarmRulesBusiness;
import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.organization.util.Merchant;
import com.turing.post.organization.util.MerchantDao;
import com.turing.post.salesmanage.util.PersonalCustom;
import com.turing.post.salesmanage.util.PersonalCustomDao;
import com.turing.post.transaction.util.MchTradDetail;
import com.turing.post.transaction.util.MchTradDetailDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;

/**
 * 规则： 同一卡号1小时内发生超过10笔的交易
 */
@Remote
@Local
@Stateless(mappedName = "antimoney.impl.AlarmRule10")
public class AlarmRule10 implements AlarmRulesBusiness {

	@PersistenceContext
	protected EntityManager _em;
	@EJB(mappedName = "transaction.impl.MchTradDetailDaoImpl")
	private MchTradDetailDao mchTradDetailDaoImpl;
	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;
	@EJB(mappedName = "salesmanage.impl.PersonalCustomDaoImpl")
	private PersonalCustomDao personalCustomDaoImpl;
	@EJB(mappedName = "antimoney.impl.AlarmInfoDaoImpl")
	private AlarmInfoDao alarmInfoDaoImpl;
	@EJB(mappedName = "antimoney.impl.AlarmInfoDetailDaoImpl")
	private AlarmInfoDetailDao alarmInfoDetailDaoImpl;

	@EJB(mappedName = "organization.impl.MerchantDaoImpl")
	private MerchantDao merchantDaoImpl;
	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao activateCardDaoImpl;

	@Override
	@TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRES_NEW)
	public void runAlarmRules(String issueCompanyNo, Date tranDate,
			AlarmRule alarmRule) throws PCPSApplicationException {
		String ruleParameter = "";// 规则
		int ruleHour = 0;// 规则小时
		int transCount = 0;// 规则笔数
		MchTradDetail mtd = null;
		int almCount = 0;// 连续的交易笔数
		int mtdsSize = 0;// 相关流水数量
		Date nextDate = null;// 下一个交易时间
		try {
			if (!PCPSUtil.isEmpty(issueCompanyNo) || tranDate != null
					|| alarmRule != null) {
				// 得到规则参数
				ruleParameter = alarmRule.getRuleParameter();
			}
			if (!PCPSUtil.isEmpty(ruleParameter)) {
				// 给定义的参数赋值
				String[] parameter = ruleParameter.split(":");
				if (parameter.length > 0) {
					ruleHour = parameter[0] == null ? 0 : Integer
							.parseInt(parameter[0]);
					transCount = parameter[1] == null ? 0 : Integer
							.parseInt(parameter[1]);
				}
			}

			// 查询出超过transCount次数的交易卡号
			List<Object[]> mchTradDetaillist = mchTradDetailDaoImpl
					.getMchTradDetailByTime(issueCompanyNo, tranDate,
							transCount);
			if (mchTradDetaillist != null && mchTradDetaillist.size() > 0) {
				Object[] obj = null;
				ActivateCard activateCard = null;
				PersonalCustom pc = null;
				for (int i = 0; i < mchTradDetaillist.size(); i++) {
					obj = mchTradDetaillist.get(i);
					// 根据卡号检索实体卡对象
					activateCard = activateCardDaoImpl
							.getActivateCardByCardNo(obj[0].toString());
					if (activateCard == null) {
						continue;
					}
					if (activateCard.getOwnerId() == null) {
						continue;
					}
					// 得到持卡人信息
					pc = personalCustomDaoImpl
							.getPersonalCustomByPersonalId(activateCard
									.getOwnerId());
					if (pc == null) {
						continue;
					}
					// 获取某卡号某账务日期内的所有交易详细
					List<MchTradDetail> list = mchTradDetailDaoImpl
							.getMchTradDetailByCardNoAndTranDate(obj[0]
									.toString(), tranDate);
					mtdsSize = list.size();
					// 循环明细信息
					for (int j = 0; j < mtdsSize; j++) {
						mtd = list.get(j);
						nextDate = getDateAddHours(mtd.getTranTime(), ruleHour);
						almCount = mchTradDetailDaoImpl
								.getMchTradDetailByCardNoAndTranDate(mtd
										.getCardNo(), mtd.getTranTime(),
										nextDate, tranDate);
						if (almCount >= transCount) {
							// 预警开始
							List<MchTradDetail> detailList = mchTradDetailDaoImpl
									.getMchTradDetailByCardNo(
											mtd.getTranTime(), nextDate, mtd
													.getCardNo(), tranDate);
							if (detailList != null && detailList.size() > 0) {
								// 增加风险预警信息
								releaseAlarm(detailList, issueCompanyNo,
										alarmRule, pc.getName(), mtd
												.getMerchantNo(), tranDate);
							}
						}
					}
				}
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 发布风险信息
	 * 
	 * @param tranDate
	 * @param alarmRule
	 * @param issueCompany
	 * 
	 * @param alarmOrders存在风险的销售单
	 * @throws PCPSApplicationException
	 */
	private void releaseAlarm(List<MchTradDetail> list, String issuecompanyno,
			AlarmRule alarmRule, String pername, String merchantno,
			Date tranDate) throws PCPSApplicationException {
		try {
			AlarmInfo alarmInfo = new AlarmInfo();
			Merchant merchant = merchantDaoImpl
					.getMerchantByMerchantNo(merchantno);
			alarmInfo.setAlarmRuleId(alarmRule.getAlarmRuleId());
			alarmInfo.setIssueCompanyNo(issuecompanyno);
			alarmInfo.setBranchNo(merchant.getMerchantNo());
			alarmInfo.setBranchName(merchant.getMerchantName());
			alarmInfo.setAlarmTime(commonDaoImpl.getDatabaseSysTime());

			alarmInfo.setRiskCustomName(pername);
			alarmInfo.setAlarmReason(alarmRule.getAlarmRuleDesc());
			alarmInfo.setDealStatus("0");

			BigInteger alarmInfoId = alarmInfoDaoImpl.getMaxAlarmInfoId();
			alarmInfo.setAlarmInfoId(alarmInfoId);
			// 插入预警信息
			alarmInfoDaoImpl.insertAlarmInfo(alarmInfo);
			MchTradDetail mchTradDetail = null;
			for (int i = 0; i <= list.size(); i++) {
				mchTradDetail = list.get(i);
				AlarmInfoDetail alarmInfoDetail = new AlarmInfoDetail();
				alarmInfoDetail.setAlarmInfoId(alarmInfoId);
				alarmInfoDetail.setSeqNo(i);
				alarmInfoDetail.setBusinessType("3");
				alarmInfoDetail.setMerchantNo(mchTradDetail.getMerchantNo());
				alarmInfoDetail.setTranDate(tranDate);
				alarmInfoDetail.setTranSeqNo(mchTradDetail.getTranSeqNo());
				alarmInfoDetailDaoImpl.insertAlarmInfoDetail(alarmInfoDetail);
			}
		} catch (Exception e) {
		}
	}

	@SuppressWarnings("unused")
	private Date getDateAddHours(Date tranTime, int ruleHour) {
		Calendar cal = java.util.Calendar.getInstance();
		cal.setTime(tranTime);
		cal.add(Calendar.HOUR, ruleHour);
		tranTime = cal.getTime();
		return tranTime;
	}
}
